<template>
  <div class="maxBox">
    <div class="header">
      <el-row>
        <el-col :span="24">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item separator-class="el-icon-arrow-right">首页</el-breadcrumb-item>
            <el-breadcrumb-item>入账</el-breadcrumb-item>
          </el-breadcrumb>
        </el-col>
      </el-row>
    </div>
    <el-form ref="form" :model="form" label-width="80px">
      <!-- <el-form-item label="金额" prop="amount">
        <el-input type="number" clearable v-model.number="form.amount"></el-input>
      </el-form-item> -->

      <div class="">
        <div class="column">
          <div class="itemBox" v-for="(item, index) in form.enterData" :key="index">
            <el-form-item :label="'借方' + (index + 1)" :prop="`enterData[${index}].subjectCode`" :rules="enterRules.subjectCode">
              <el-cascader clearable :props="props" :options="options" v-model="item.subjectCode" placeholder="请选择借方" style="width: 100%" filterable></el-cascader>
            </el-form-item>
            <el-form-item label="金额" :prop="`enterData[${index}].amount`" :rules="enterRules.amount">
              <el-input v-model="item.amount" placeholder="请输入金额" type="number"></el-input>
            </el-form-item>
            <el-form-item label="备注" :prop="`enterData[${index}].memo`" :rules="enterRules.memo">
              <el-input clearable :autosize="{ minRows: 5, maxRows: 10 }" v-model="item.memo"></el-input>
            </el-form-item>
            <div class="wrapBox">

              <el-form-item label="图片" class="imgItem">
                <el-upload ref="up" class="upload-demo" action="https://www.xmssj.com/dl/api/reimbursed/uploadFile" :on-preview="handlePreview" :on-remove="file=>handleRemove(file,item)" multiple :limit="3" :http-request="e=>file(e,item)" list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>

              <div class="flex justify-between" style="min-width:80px">
                <i class="el-icon-circle-plus-outline" v-if="index == form.enterData.length - 1" @click="add(1)"></i>
                <i class="el-icon-remove-outline" v-if="
                form.enterData &&
                form.enterData.length > 1
              " @click="del(1, index)"></i>
              </div>
            </div>
          </div>
        </div>
        <div class="line"></div>
        <div class="column">
          <div class="itemBox" v-for="(item, index) in form.outData" :key="index">
            <el-form-item :label="'贷方' + (index + 1)" :prop="`outData[${index}].subjectCode`" :rules="outRules.subjectCode">
              <el-cascader clearable :props="props" :options="options" v-model="item.subjectCode" placeholder="请选择贷方" style="width: 100%" filterable></el-cascader>
            </el-form-item>

            <el-form-item label="金额" :prop="`outData[${index}].amount`" :rules="outRules.amount">
              <el-input v-model="item.amount" placeholder="请输入金额" type="number"></el-input>
            </el-form-item>
            <el-form-item label="备注" :prop="`outData[${index}].memo`" :rules="outRules.memo">
              <el-input clearable :autosize="{ minRows: 5, maxRows: 10 }" v-model="item.memo"></el-input>
            </el-form-item>
            <div class="wrapBox">
              <el-form-item label="图片" class="imgItem">
                <el-upload ref="up" class="upload-demo" action="https://www.xmssj.com/dl/api/reimbursed/uploadFile" :on-preview="handlePreview" :on-remove="file=>handleRemove(file,item)" multiple :limit="3" :http-request="e=>file(e,item)" list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>

              <div class="flex justify-between" style="min-width:80px">
                <i class="el-icon-circle-plus-outline" v-if="index == form.outData.length - 1" @click="add(2)"></i>
                <i class="el-icon-remove-outline" v-if="
                  form.outData && form.outData.length > 1
                " @click="del(2, index)"></i>
              </div>
            </div>
          </div>
        </div>
      </div>

      <el-form-item class="footerClass">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="onSubmit" v-loading.fullscreen.lock="fullscreenLoading">提交</el-button>
      </el-form-item>
    </el-form>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { subjectList, allSubjectList, inEntry } from "../../network/business";
import { upload } from "../../network/job";
export default {
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: "",
      form: {
        outData: [
          {
            subjectCode: "",
            amount: "",
            memo: "",
            img: [],
          },
        ],
        enterData: [
          {
            subjectCode: "",
            amount: "",
            memo: "",
            img: [],
          },
        ],
      },
      props: {
        label: "subjectName",
        value: "subjectCode",
        checkStrictly: true,
        children: "list",
      },
      options: [],
      list: [],
      loading: false,
      fullscreenLoading: false,
      outRules: {
        subjectCode: [
          { required: true, message: "请选择贷方", trigger: "blur" },
        ],
        amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
        memo: [{ required: true, message: "请输入备注", trigger: "blur" }],
      },
      enterRules: {
        subjectCode: [
          { required: true, message: "请选择借方", trigger: "blur" },
        ],
        amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
        memo: [{ required: true, message: "请输入备注", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getSubjectList();
  },
  methods: {
    handleRemove(file, item) {
      var a = item.img.find((items) => items.uid === file.uid);
      if (a) {
        item.img.remove(a);
      }
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    file(e, item) {
      let file = new FormData();
      file.append("img", e.file);
      upload(file).then((v) => {
        if (v.code == 200) {
          if (!item.img) {
            item.img = [];
          }
          item.img.push({
            url: v.data,
            uid: e.file.uid,
          });
        } else {
          this.$message.error("上传图片失败");
        }
      });
    },

    add(type) {
      let str = type == 1 ? "enterData" : "outData";
      this.form[str].push({
        subjectCode: "",
        amount: "",
      });
    },
    del(type, index) {
      let str = type == 1 ? "enterData" : "outData";
      this.form[str].splice(index, 1);
    },
    onSubmit() {
      
      this.$refs.form.validate(async (val) => {
        if (!val) {
          this.$message.error("请录入必填项");
          return;
        }
        this.fullscreenLoading = true;
        let data = this.$copy(this.form);
        data.enterData.forEach((item) => {
          item.subjectCode = item.subjectCode[item.subjectCode.length - 1];
          if (item.img) {
            item.img = item.img.map((items) => items.url);
          }
        });
        data.outData.forEach((item) => {
          item.subjectCode = item.subjectCode[item.subjectCode.length - 1];
          if (item.img) {
            item.img = item.img.map((items) => items.url);
          }
        });
        try {
          let res = await inEntry(data);
          if (res) this.fullscreenLoading = false;
          if (res.code == 200) {
            this.$alert(res.msg, "温馨提示");
            this.resetForm();
          } else {
            this.$alert(res.msg, "错误");
          }
        } catch (error) {
          this.fullscreenLoading = false;
        }
      });
    },
    resetForm() {
      this.form = {
        outData: [
          {
            subjectCode: "",
            amount: "",
            memo: "",
            img: [],
          },
        ],
        enterData: [
          {
            subjectCode: "",
            amount: "",
            memo: "",
            img: [],
          },
        ],
      };
      
      var list = this.$refs.up;
      if (list) {
        list.forEach((item) => {
          item.clearFiles();
        });
      }
      this.$refs.form.resetFields();
    },
    async addUser() {
      this.showLoading();
      this.getAllList(this.list);
    },

    // 递归得到所有的科目选项
    async getAllList(list) {
      let i = 0;
      if (list && list.length > 0) {
        list.forEach((item) => {
          allSubjectList(item.subjectCode).then((res) => {
            i++;
            item["list"] = res.data.content;
            if (i == list.length) {
              this.closeLoading();
              this.options = this.setArr(list);
            }
          });
        });
      }
      return list;
    },

    //设置子级没有值的时候就删除
    setArr(list) {
      if (list && list.length > 0) {
        list.forEach((item) => {
          if (item.list && item.list.length > 0) {
            this.setArr(item.list);
          } else {
            delete item.list;
          }
        });
      }
      return list;
    },
    showLoading() {
      this.loading = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    closeLoading() {
      this.loading.close();
    },

    async getChildren(code) {
      return allSubjectList(code).then((res) => {
        if (
          res.code == 200 &&
          res.data &&
          res.data.content &&
          res.data.content.length > 0
        ) {
          res.data.content.forEach((item) => {
            if (item.originally) item.disabled = true;
          });
          return res.data.content;
        }
      });
    },
    async getSubjectList() {
      let res = await subjectList();
      if (res.code == 200 && res.data && res.data.content) {
        this.list = res.data.content;
        this.addUser();
      } else {
        this.$error(res.msg);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.maxBox ::v-deep {
  .header {
    margin-bottom: 20px;
  }
  .el-form {
    padding-top: 20px;
    .column {
      flex: 0.48;
    }
    .line {
      height: 1px;
      background: #ddd;
      margin: 10px 0 20px 0;
    }
    .itemBox {
      display: flex;
      align-items: center;
      .wrapBox {
        display: flex;
        align-items: center;
        .imgItem {
          display: flex;
          align-items: center;
          .el-form-item__content {
            margin-left: 0 !important;
            .upload-demo {
              display: flex;
              align-items: center;
              .el-upload {
                margin-right: 20px;
              }
            }
          }
        }
      }
      .el-form-item__content {
        display: flex;
        align-items: center;
      }
      i {
        font-size: 28px;
        cursor: pointer;
        margin-left: 10px;
        margin-bottom: 20px;
      }
      i:active {
        color: #999;
      }
    }
    .footerClass {
      margin-top: 30px;
      text-align: center;
    }
  }
  // 处理input type = number的上下箭头
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"] {
    -moz-appearance: textfield;
  }
}
</style>